<template>
  <div class="model-type-tree-container">
    <el-card shadow="always">
      <el-row justify="space-between" align="middle">
        <h3>模型类型</h3>
        <el-button type="primary" @click="showTypeMaintenanceDialog">类型维护</el-button>
      </el-row>
      <el-tree
        ref="treeRef"
        :data="modelTypes"
        default-expand-all
        node-key="typeCode"
        :props="treeProps"
        current-node-key="W"
        highlight-current
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
            :content="node.label + '(' + data.rNum + ')'"
            :disabled="node.label.length < 8"
          >
            <span :id="'A' + data.typeCode"
              >{{ node.label }}{{ data.rNum ? '(' + data.rNum + ')' : '' }}
            </span>
          </el-tooltip>
        </template>
      </el-tree>
    </el-card>

    <!-- Type Maintenance Dialog -->
    <el-dialog
      v-model="typeMaintenanceDialogVisible"
      title="类型维护"
      style="height: 80vh"
      width="60%"
    >
      <el-row justify="space-between">
        <div class="model-type-tree-content">
          <h4>模型类型树</h4>
          <!-- <el-tree
            :data="modelTypes"
            default-expand-all
            node-key="id"
            :props="treeProps"
            :expand-on-click-node="false"
          /> -->
          <el-tree
            :data="modelTypeTree"
            :props="{
              children: 'children',
              label: 'typeName'
            }"
            node-key="typeCode"
            default-expand-all
            :expand-on-click-node="false"
            @node-click="handleTypeNodeClick"
            highlight-current
            ref="appTreeRef"
          >
            <template #default="{ node, data }">
              <el-tooltip
                class="item"
                effect="dark"
                placement="top"
                :content="node.label + '(' + data.rNum + ')'"
                :disabled="node.label.length < 8"
              >
                <span
                  :id="'A' + data.typeCode"
                  style="
                    width: 150px;
                    display: inline-block;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                  >{{ node.label }} {{ switchData(data) }}</span
                >
              </el-tooltip>
            </template>
          </el-tree>
        </div>

        <div class="info-list-container">
          <h4>模型类型信息列表</h4>
          <el-button type="primary" size="small" @click="showAddSubclassDialog">新增子类</el-button>
          <el-table :data="selectedTypeData" style="width: 100%" border>
            <el-table-column prop="typeName" label="类型名称" align="center" />
            <el-table-column prop="typeFid" label="类型标识" align="center" />
            <el-table-column prop="typeCode" label="类型编码" align="center" />
            <el-table-column prop="ord" label="位置号" align="center" />
            <el-table-column fixed="right" label="操作" width="120" align="center">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="showAddSubclassDialog(row)"
                  >修改</el-button
                >
                <el-button link type="danger" size="small" @click="deleteRow(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-row>

      <!-- Add Subclass Dialog -->
      <el-dialog v-model="addSubclassDialogVisible" :title="dialogTitle" width="30%">
        <el-form :model="newSubclassForm" label-width="120px" ref="formRef" :rules="formRules">
          <el-form-item label="类型名称" prop="typeName">
            <el-input v-model="newSubclassForm.typeName" />
          </el-form-item>
          <el-form-item label="类型标识" prop="typeFid">
            <el-input v-model="newSubclassForm.typeFid" />
          </el-form-item>
          <el-form-item label="类型编码" prop="typeCode">
            <el-input v-model="newSubclassForm.typeCode" />
          </el-form-item>
          <el-form-item label="位置号" prop="ord">
            <el-input-number v-model="newSubclassForm.ord" :min="1" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelAddSubclass">取消</el-button>
            <el-button type="primary" @click="handleSaveSubInfo">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import {
  ElCard,
  ElRow,
  ElButton,
  ElTree,
  ElDialog,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessageBox
} from 'element-plus'

import {
  getModelCategories,
  verifyCategories,
  getModelCategoriesList,
  deleteModelCategories,
  saveCategories
} from '@/services/modules/model.js'
import { conversionTreeLabel } from '@/utils/func.js'
const formRef = ref(null)
const modelTypes = ref([])
const modelTypeTree = ref([])
const dialogTitle = ref('新增子类')
const treeProps = ref({ children: 'children', label: 'typeName' })
const appTreeRef = ref(null)
const treeRef = ref(null)
const typeMaintenanceDialogVisible = ref(false)
const addSubclassDialogVisible = ref(false)
const verifyTypeNameIsValidate = async (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入类型名称'))
  } else {
    // 验证类型名称是否存在
    const result = await verifyValueIsExist('typeName', value)

    if (result === 1) {
      callback(new Error('此类型名称已存在，请重新输入'))
    } else {
      callback()
    }
  }
}

const verifyTypeFidIsValidate = async (rule, value, callback) => {
  if (value == '') {
    callback(new Error('请输入类型标识'))
  } else {
    // 验证类型标识是否存在
    const result = await verifyValueIsExist('typeFid', value)
    if (result === 1) {
      callback(new Error('此类型标识已存在，请重新输入'))
    } else {
      callback()
    }
  }
}

const verifyTypeCodeIsValidate = async (rule, value, callback) => {
  if (value == '') {
    callback(new Error('请输入类型编码'))
  } else {
    // 验证类型编码是否存在
    const result = await verifyValueIsExist('typeCode', value)
    if (result === 1) {
      callback(new Error('此类型编码已存在，请重新输入'))
    } else {
      callback()
    }
  }
}

/**
 * 判断输入的值是否存在
 * @param key 判断的建
 * @param val 判断输入的值是否存在
 */
const verifyValueIsExist = (key, val) => {
  return new Promise((resolve) => {
    verifyCategories({ key, val, id: newSubclassForm.value.id }).then((res) => {
      if (res.code === 200) {
        resolve(res.data.result)
      }
    })
  })
}
const switchData = (data) => {
  if (data.children && data.children.length > 0) {
    return `(${data.children.length})`
  }
  return ''
}
/**
 * 表单验证规则
 */
const formRules = ref({
  typeName: [{ required: true, validator: verifyTypeNameIsValidate, trigger: 'blur' }],
  typeFid: [{ required: true, validator: verifyTypeFidIsValidate, trigger: 'blur' }],
  typeCode: [{ required: true, validator: verifyTypeCodeIsValidate, trigger: 'blur' }],
  ord: [{ required: true, message: '位置号不能为空', trigger: 'blur' }]
})
const selectedTypeData = ref([])
const emit = defineEmits(['nodeClick'])
const newSubclassForm = ref({
  id: '',
  typeName: '',
  typeCode: '',
  typeFid: '',
  parentCode: '',
  ord: 1
})
const parentTypeCode = ref('')
function showTypeMaintenanceDialog() {
  typeMaintenanceDialogVisible.value = true
  getModelCategoriesListData({ typeCode: 'W' })
  nextTick(() => {
    appTreeRef.value.setCurrentKey('W')
  })
}

function handleNodeClick(data) {
  emit('nodeClick', data)
}
function getModelCategoriesListData(data) {
  const params = {
    typeName: '',
    typeCode: data.typeCode,
    pageSize: 10,
    pageNum: 1
  }
  getModelCategoriesList(params).then((res) => {
    if (res.code == 200) {
      selectedTypeData.value = res.data.list
    }
  })
}
function handleTypeNodeClick(data) {
  appTreeRef.value.setCurrentKey(data.typeCode)
  parentTypeCode.value = data.typeCode
  newSubclassForm.value.parentCode = data.typeCode
  getModelCategoriesListData(data)
}
/**
 * 获取父界面当前选中的节点
 */
const handleGetModelTreeNodeCode = (data) => {
  if (data) {
    nextTick(() => {
      // 滚动到当前选中的节点
      const currentDom = appTreeRef.value.$el.querySelector('#A' + data)
      if (currentDom) {
        currentDom.scrollIntoView({ behavior: 'smooth', block: 'center' })
      }
      // 设置当前选中的节点
      appTreeRef.value.setCurrentKey(data)

      // 延迟
      setTimeout(() => {
        // 点击当前节点-事件
        handleTypeNodeClick(appTreeRef.value.getCurrentNode())
      }, 500)
    })
  }
}
//保存子类
function handleSaveSubInfo() {
  formRef.value.validate((valid) => {
    if (valid) {
      saveCategories(newSubclassForm.value).then((res) => {
        if (res.code === 200) {
          ElMessage({
            message: '保存成功',
            type: 'success'
          })
          addSubclassDialogVisible.value = false
          getModelCategoriesData()
        }
      })
      // Reset form
      resetNewSubclassForm()
      addSubclassDialogVisible.value = false
    }
  })
}
function showAddSubclassDialog(row) {
  if (row.id) {
    newSubclassForm.value.id = row.id
    newSubclassForm.value.typeFid = row.typeFid
    newSubclassForm.value.ord = row.ord
    newSubclassForm.value.typeName = row.typeName
    newSubclassForm.value.typeCode = row.typeCode
    newSubclassForm.value.parentCode = row.parentCode
    dialogTitle.value = '编辑子类'
  } else {
    newSubclassForm.value.id = undefined
    dialogTitle.value = '新增子类'
    newSubclassForm.value.typeFid = ''
    newSubclassForm.value.ord = ''
    newSubclassForm.value.typeName = ''
    newSubclassForm.value.typeCode = ''
  }
  addSubclassDialogVisible.value = true
}
function getModelCategoriesData() {
  getModelCategories({ modelName: '' }).then((res) => {
    modelTypes.value = [JSON.parse(JSON.stringify(res.data))]
    modelTypeTree.value = [JSON.parse(JSON.stringify(res.data))]
  })
  handleGetModelTreeNodeCode(parentTypeCode.value)
}
function initData() {
  getModelCategoriesData()
}

function cancelAddSubclass() {
  resetNewSubclassForm()
  addSubclassDialogVisible.value = false
}

function resetNewSubclassForm() {
  newSubclassForm.value.id = ''
  newSubclassForm.value.typeName = ''
  newSubclassForm.value.typeCode = ''
  newSubclassForm.value.typeFid = ''
  newSubclassForm.value.ord = ''
  formRef.value.resetFields()
}

function deleteRow(row) {
  if (row.rNum > 0) {
    return ElMessage({
      message: '请先删除子集模型类型',
      type: 'error'
    })
  } else {
    ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        deleteModelCategories({ id: row.id }).then((res) => {
          if (res.code === 200) {
            ElMessage({
              message: '删除成功',
              type: 'success'
            })
            getModelCategoriesData()
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除'
        })
      })
  }
}
onMounted(() => {
  initData()
})
</script>

<style scoped lang="less">
:deep(.el-tree-node) {
  font-size: 15px;
  &.is-focusable.is-current {
    > div:nth-of-type(1) {
      color: #409eff;
      font-weight: 600;
    }
  }
  .el-tree-node__content {
    margin-top: 5px;
  }
}
.model-type-tree-container {
  border-right: 1px solid rgb(237, 237, 237);
  ::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
  }
  .el-tree {
    height: 75vh;

    overflow-y: auto;
  }
  /* background-color: #f5f7fa; */
}
.model-type-tree-content {
  width: 17%;
  border-right: 1px solid rgb(237, 237, 237);

  .el-tree {
    height: 58vh;
    padding-right: 20px;
    overflow-y: auto;
  }
}
.info-list-container {
  width: 80%;
  margin-left: 1%;
  vertical-align: top;
}
.el-table {
  margin-top: 10px;
}
</style>
